//
//  NSDate+Extend.m
//  EPTool
//
//  Created by shiqing guo on 2018/5/8.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "NSDate+Extend.h"

static int localAndServerGap = 0;

@implementation NSDate (Extend)

- (NSString *)transformDateForListCell
{
    NSDate* nowDate = [NSDate date];
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setFirstWeekday:2];//设定从星期一开始
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSCalendarUnitYear, NSCalendarUnitMonth, NSCalendarUnitDay等）
    NSDateComponents *nowDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | kCFCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear fromDate:nowDate];
    
    NSDateComponents *selfDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:self];
    
    NSDateComponents *weeDateComponents = [[NSDateComponents alloc] init];
    [weeDateComponents setCalendar:[NSCalendar currentCalendar]];
    weeDateComponents.year = selfDateComponents.year;
    weeDateComponents.month = selfDateComponents.month;
    weeDateComponents.day = selfDateComponents.day;
    weeDateComponents.hour = 0;
    weeDateComponents.minute = 0;
    weeDateComponents.second = 0;
    
    if (nowDateComponents.year == selfDateComponents.year) {
        //同一年
        if (nowDateComponents.month == selfDateComponents.month) {
            //同一个月
            if (nowDateComponents.day == selfDateComponents.day) {
                //同一天
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString* dateString = [dateFormatter stringFromDate:self];
                return dateString;
            } else if (nowDateComponents.day -1 == selfDateComponents.day){
                //昨天
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString* dateString = [dateFormatter stringFromDate:self];
                NSString *string = [NSString stringWithFormat:@"昨天 %@",dateString];
                return string;
            } else {
                if (nowDateComponents.weekOfYear == selfDateComponents.weekOfYear) {
                    NSArray* weekdays = @[@"temp",@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
                    NSString* dateString = weekdays[selfDateComponents.weekday];
                    return dateString;
                }else {
                    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"MM月dd日"];
                    NSString* dateString = [dateFormatter stringFromDate:self];
                    return dateString;
                }
            }
        } else {
            NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM月dd日"];
            NSString* dateString = [dateFormatter stringFromDate:self];
            return dateString;
        }
    } else {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
        NSString* dateString = [dateFormatter stringFromDate:self];
        return dateString;
    }
}

- (NSString *)transformDateForMainCell
{
    NSDate* nowDate = [NSDate date];
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [greCalendar setFirstWeekday:2];//设定从星期一开始
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSCalendarUnitYear, NSCalendarUnitMonth, NSCalendarUnitDay等）
    NSDateComponents *nowDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:nowDate];
    
    NSDateComponents *selfDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:self];
    
    NSDateComponents *weeDateComponents = [[NSDateComponents alloc] init];
    [weeDateComponents setCalendar:[NSCalendar currentCalendar]];
    weeDateComponents.year = selfDateComponents.year;
    weeDateComponents.month = selfDateComponents.month;
    weeDateComponents.day = selfDateComponents.day;
    weeDateComponents.hour = 0;
    weeDateComponents.minute = 0;
    weeDateComponents.second = 0;
    
    if (nowDateComponents.year == selfDateComponents.year) {
        //同一年
        if (nowDateComponents.month == selfDateComponents.month) {
            //同一个月
            if (nowDateComponents.day == selfDateComponents.day) {
                //同一天
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString* dateString = [dateFormatter stringFromDate:self];
                return dateString;
            } else if (nowDateComponents.day -1 == selfDateComponents.day){
                //昨天
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString* dateString = [dateFormatter stringFromDate:self];
                NSString *string = [NSString stringWithFormat:@"昨天 %@",dateString];
                return string;
            } else {
                if (nowDateComponents.weekOfYear == selfDateComponents.weekOfYear) {
                    NSArray* weekdays = @[@"temp",@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
                    NSString* dateString = weekdays[selfDateComponents.weekday];
                    return dateString;
                }else {
                    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
                    NSString* dateString = [dateFormatter stringFromDate:self];
                    return dateString;
                }
            }
        } else {
            NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
            NSString* dateString = [dateFormatter stringFromDate:self];
            return dateString;
        }
    } else {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
        NSString* dateString = [dateFormatter stringFromDate:self];
        return dateString;
    }
}


//时间提示字符串，聊天窗口中的
- (NSString *)promptDateString {
    NSDate* nowDate = [NSDate date];
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSCalendarUnitYear, NSCalendarUnitMonth, NSCalendarUnitDay等）
    NSDateComponents *nowDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:nowDate];
    
    NSDateComponents *selfDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:self];
    
    NSDateComponents *weeDateComponents = [[NSDateComponents alloc] init];
    [weeDateComponents setCalendar:[NSCalendar currentCalendar]];
    weeDateComponents.year = selfDateComponents.year;
    weeDateComponents.month = selfDateComponents.month;
    weeDateComponents.day = selfDateComponents.day;
    weeDateComponents.hour = 0;
    weeDateComponents.minute = 0;
    weeDateComponents.second = 0;
    
    NSString* lastComponents = nil;
    //    NSString* twoComponent = nil;
    NSInteger hour = selfDateComponents.hour;
    
    if (selfDateComponents.minute < 10) {
        lastComponents = [NSString stringWithFormat:@"%li:0%li",(long)hour,(long)selfDateComponents.minute];
    } else {
        lastComponents = [NSString stringWithFormat:@"%li:%li",(long)hour,(long)selfDateComponents.minute];
    }
    
    NSString* dateString = nil;
    if (nowDateComponents.day == selfDateComponents.day) {//同一天
        dateString = lastComponents;
    } else if (nowDateComponents.year == selfDateComponents.year) {//同一年
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM-dd"];
        dateString = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:self],lastComponents];
    } else {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yy-MM-dd"];
        dateString = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:self],lastComponents];
    }
    return dateString;
}

+ (void)setServerTime:(int)serverTime
{
    int localTime = [[NSDate date] timeIntervalSince1970];
    localAndServerGap = serverTime - localTime;
}

+ (NSUInteger)messageDate
{
    int localDate = [[NSDate date] timeIntervalSince1970];
    return localDate + localAndServerGap;
}


/**
 *  时间转换
 *
 *  @param timeSince1970 1970标准时间
 *
 *  @return 2001标准时间
 */
+ (NSTimeInterval)timeSinceReferenceWithTimeSince1970:(NSTimeInterval)timeSince1970
{
    return [NSDate dateWithTimeIntervalSince1970:timeSince1970].timeIntervalSinceReferenceDate;
}

+ (NSTimeInterval)timeSinceReferenceWithTimeSince2001:(NSTimeInterval)timeSince2001
{
    return [[NSDate dateWithTimeIntervalSinceReferenceDate:timeSince2001] timeIntervalSince1970];
}

/*
 * This guy can be a little unreliable and produce unexpected results,
 * you're better off using daysAgoAgainstMidnight
 */
//获取年月日如:19871127.
- (NSString *)getFormatYearMonthDay
{
    NSString *string = [NSString stringWithFormat:@"%u%02u%02u",(uint)[self getYear],(uint)[self getMonth],(uint)[self getDay]];
    return string;
}
//返回当前月一共有几周(可能为4,5,6)
- (int )getWeekNumOfMonth
{
    return [[self endOfMonth] getWeekOfYear] - [[self beginningOfMonth] getWeekOfYear] + 1;
}
//该日期是该年的第几周
- (int )getWeekOfYear
{
    int i;
    int year = (int)[self getYear];
    NSDate *date = [self endOfWeek];
    for (i = 1;[[date dateAfterDay:-7 * i] getYear] == year;i++)
    {
    }
    return i;
}
//返回day天后的日期(若day为负数,则为|day|天前的日期)
- (NSDate *)dateAfterDay:(int)day
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    // NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
    // to get the end of week for a particular date, add (7 - weekday) days
    [componentsToAdd setDay:day];
    NSDate *dateAfterDay = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
    
    return dateAfterDay;
}
//month个月后的日期
- (NSDate *)dateAfterMonth:(int)month
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
    [componentsToAdd setMonth:month];
    NSDate *dateAfterMonth = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
    
    return dateAfterMonth;
}
//获取日
- (NSUInteger)getDay{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dayComponents = [calendar components:(NSCalendarUnitDay) fromDate:self];
    return [dayComponents day];
}
//获取月
- (NSUInteger)getMonth
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dayComponents = [calendar components:(NSCalendarUnitMonth) fromDate:self];
    return [dayComponents month];
}
//获取日
- (NSString *)getDayString{
    NSUInteger day = [self getDay];
    if(day<10)
    {
        return [NSString stringWithFormat:@"0%d", (int)day];
    }
    else
    {
        return [NSString stringWithFormat:@"%d", (int)day];
    }
}
//获取月
- (NSString *)getMonthString
{
    int month = (int)[self getMonth];
    if(month<10)
    {
        return [NSString stringWithFormat:@"0%d", month];
    }
    else
    {
        return [NSString stringWithFormat:@"%d", month];
    }
}
//获取年
- (NSString *)getYearString
{
    int year = (int)[self getYear];
    if(year<10)
    {
        return [NSString stringWithFormat:@"0%d", year];
    }
    else
    {
        return [NSString stringWithFormat:@"%d", year];
    }
}
//获取年
- (NSUInteger)getYear
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dayComponents = [calendar components:(NSCalendarUnitYear) fromDate:self];
    return [dayComponents year];
}
//获取小时
- (NSInteger)getHour {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags =NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour|NSCalendarUnitMinute;
    NSDateComponents *components = [calendar components:unitFlags fromDate:self];
    NSInteger hour = [components hour];
    return hour;
}
//获取月
- (NSString *)getHourString
{
    int hour = (int)[self getHour];
    if(hour<10)
    {
        return [NSString stringWithFormat:@"0%d", hour];
    }
    else
    {
        return [NSString stringWithFormat:@"%d", hour];
    }
}
//获取分钟
- (NSUInteger)getMinute {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags =NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour|NSCalendarUnitMinute;
    NSDateComponents *components = [calendar components:unitFlags fromDate:self];
    NSInteger minute = [components minute];
    return minute;
}
//获取月
- (NSString *)getMinuteString
{
    NSUInteger minute = [self getMinute];
    if(minute<10)
    {
        return [NSString stringWithFormat:@"0%u", (uint)minute];
    }
    else
    {
        return [NSString stringWithFormat:@"%u", (uint)minute];
    }
}

- (NSInteger)getHour:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags =NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour|NSCalendarUnitMinute;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    NSInteger hour = [components hour];
    return hour;
}

- (NSInteger)getMinute:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags =NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour|NSCalendarUnitMinute;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    NSInteger minute = [components minute];
    return minute;
}

//在当前日期前几天
- (NSUInteger)daysAgo {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitDay)
                                               fromDate:self
                                                 toDate:[[NSDate alloc] init]
                                                options:0];
    return [components day];
}
//午夜时间距今几天
- (NSUInteger)daysAgoAgainstMidnight {
    // get a midnight version of ourself:
    NSDateFormatter *mdf = [[NSDateFormatter alloc] init];
    [mdf setDateFormat:@"yyyy-MM-dd"];
    NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];
    
    return (int)[midnight timeIntervalSinceNow] / (60*60*24) *-1;
}

- (NSString *)stringDaysAgo {
    return [self stringDaysAgoAgainstMidnight:YES];
}

- (NSString *)stringDaysAgoAgainstMidnight:(BOOL)flag {
    NSUInteger daysAgo = (flag) ? [self daysAgoAgainstMidnight] : [self daysAgo];
    NSString *text = nil;
    switch (daysAgo) {
        case 0:
            text = @"Today";
            break;
        case 1:
            text = @"Yesterday";
            break;
        default:
            text = [NSString stringWithFormat:@"%u days ago", (int)daysAgo];
    }
    return text;
}
//返回一周的第几天(周末为第一天)
- (NSUInteger)weekday {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *weekdayComponents = [calendar components:(NSCalendarUnitWeekday) fromDate:self];
    return [weekdayComponents weekday];
}

- (NSString *)strWeekday
{
    NSArray * arrWeek = @[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *compoments = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSWeekdayCalendarUnit fromDate:self];
    
    return [NSString stringWithFormat:@"%@",[arrWeek objectAtIndex:[compoments weekday] - 1]];
}

- (NSString *)strWeekDayWithPrefix:(NSString *)strPre
{
    NSArray * arrWeek = @[[NSString stringWithFormat:@"%@%@", strPre, @"日"],
                          [NSString stringWithFormat:@"%@%@", strPre, @"一"],
                          [NSString stringWithFormat:@"%@%@", strPre, @"二"],
                          [NSString stringWithFormat:@"%@%@", strPre, @"三"],
                          [NSString stringWithFormat:@"%@%@", strPre, @"四"],
                          [NSString stringWithFormat:@"%@%@", strPre, @"五"],
                          [NSString stringWithFormat:@"%@%@", strPre, @"六"]];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *compoments = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSWeekdayCalendarUnit fromDate:self];
    
    return [NSString stringWithFormat:@"%@",[arrWeek objectAtIndex:[compoments weekday] - 1]];
}


//计算两个时间段相差多少天

/**
 * 计算上次日期距离现在多久
 *
 * @param lastTimeStr  上次日期(需要和格式对应)
 * @param format1   上次日期格式
 * @param currentTimeStr 最近日期(需要和格式对应)
 * @param format2   最近日期格式
 *
 * @return 多少天
 */

+ (NSInteger)dayBYtimeIntervalFromLastTime:(NSString *)lastTimeStr
                            lastTimeFormat:(NSString *)format1
                             ToCurrentTime:(NSString *)currentTimeStr
                         currentTimeFormat:(NSString *)format2{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastTime = [dateFormatter1 dateFromString:lastTimeStr];
    //当前时间
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    NSDate *currentTime = [dateFormatter2 dateFromString:currentTimeStr];
    
    
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    NSInteger day = intevalTime / 60 / 60 / 24;  //差了多少天
    
    return day;
}



/**
 * 计算上次日期距离现在多久
 *
 * @param lastTime  上次日期(需要和格式对应)
 * @param format1   上次日期格式
 * @param currentTime 最近日期(需要和格式对应)
 * @param format2   最近日期格式
 *
 * @return xx分钟前、xx小时前、xx天前
 */
+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime
                        lastTimeFormat:(NSString *)format1
                         ToCurrentTime:(NSString *)currentTime
                     currentTimeFormat:(NSString *)format2{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [self timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
}

+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10) {
        return @"刚刚";
    }else if (minutes < 60){
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }else if (hours < 24){
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30){
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"M月d日";
        NSString * time = [df stringFromDate:lastDate];
        return time;
    }else if (yers >= 1){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"yyyy年M月d日";
        NSString * time = [df stringFromDate:lastDate];
        return time;
    }
    return @"";
}


//转为NSString类型的
+ (NSDate *)dateFromString:(NSString *)string {
    return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];
}

+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:format];
    NSDate *date = [inputFormatter dateFromString:string];
    return date;
}
+ (NSDate *)dateFromDate:(NSDate *)date withFormat:(NSString *)format
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:format];
    NSString *strDate = [NSDate stringFromDate:date withFormat:format];
    return [inputFormatter dateFromString:strDate];
}
+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
    return [date stringWithFormat:format];
}


+ (NSString *)stringFromString:(NSString *)string withInFormat:(NSString *)inFormat andOutFormat:(NSString *)outFormat
{
    NSDate *date = [NSDate dateFromString:string withFormat:inFormat];
    return [NSDate stringFromDate:date withFormat:outFormat];
}

+ (NSString *)stringFromDate:(NSDate *)date {
    return [date string];
}

+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed {
    /*
     * if the date is in today, display 12-hour time with meridian,
     * if it is within the last 7 days, display weekday name (Friday)
     * if within the calendar year, display as Jan 23
     * else display as Nov 11, 2008
     */
    
    NSDate *today = [[NSDate alloc] init];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *offsetComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                     fromDate:today];
    
    NSDate *midnight = [calendar dateFromComponents:offsetComponents];
    
    NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
    NSString *displayString = nil;
    
    // comparing against midnight
    if ([date compare:midnight] == NSOrderedDescending) {
        if (prefixed) {
            [displayFormatter setDateFormat:@"'at' h:mm a"]; // at 11:30 am
        } else {
            [displayFormatter setDateFormat:@"h:mm a"]; // 11:30 am
        }
    } else {
        // check if date is within last 7 days
        NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
        [componentsToSubtract setDay:-7];
        NSDate *lastweek = [calendar dateByAddingComponents:componentsToSubtract toDate:today options:0];
        if ([date compare:lastweek] == NSOrderedDescending) {
            [displayFormatter setDateFormat:@"EEEE"]; // Tuesday
        } else {
            // check if same calendar year
            NSInteger thisYear = [offsetComponents year];
            
            NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                           fromDate:date];
            NSInteger thatYear = [dateComponents year];
            if (thatYear >= thisYear) {
                [displayFormatter setDateFormat:@"MMM d"];
            } else {
                [displayFormatter setDateFormat:@"MMM d, yyyy"];
            }
        }
        if (prefixed) {
            NSString *dateFormat = [displayFormatter dateFormat];
            NSString *prefix = @"'on' ";
            [displayFormatter setDateFormat:[prefix stringByAppendingString:dateFormat]];
        }
    }
    
    // use display formatter to return formatted date string
    displayString = [displayFormatter stringFromDate:date];
    return displayString;
}

+ (NSString *)stringForDisplayFromDate:(NSDate *)date {
    return [self stringForDisplayFromDate:date prefixed:NO];
}

- (NSString *)stringWithFormat:(NSString *)format {
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:format];
    NSString *timestamp_str = [outputFormatter stringFromDate:self];
    return timestamp_str;
}

- (NSString *)string {
    return [self stringWithFormat:[NSDate dbFormatString]];
}

- (NSString *)chString {
    return [self stringWithFormat:[NSDate chFormatString]];
}

- (NSString *)dateString
{
    return [self stringWithFormat:[NSDate dateFormatString]];
}

- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle {
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateStyle:dateStyle];
    [outputFormatter setTimeStyle:timeStyle];
    NSString *outputString = [outputFormatter stringFromDate:self];
    return outputString;
}

//返回周天的的开始时间
- (NSDate *)beginningOfWeek {
    // largely borrowed from "Date and Time Programming Guide for Cocoa"
    // we'll use the default calendar and hope for the best
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *beginningOfWeek = nil;
    BOOL ok = [calendar rangeOfUnit:NSCalendarUnitWeekOfYear startDate:&beginningOfWeek
                           interval:NULL forDate:self];
    if (ok) {
        
        // 转成东八区
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate:beginningOfWeek];
        beginningOfWeek = [beginningOfWeek dateByAddingTimeInterval:interval];
        
        // 如果是周日减去6天
        if ([[self getYearString] isEqualToString:[beginningOfWeek getYearString]] &&
            [[self getMonthString] isEqualToString:[beginningOfWeek getMonthString]] &&
            [[self getDayString] isEqualToString:[beginningOfWeek getDayString]]) {
            return [NSDate dateWithTimeInterval:-24*60*60*6 sinceDate:beginningOfWeek];
        }
        
        return [NSDate dateWithTimeInterval:24*60*60*1+1 sinceDate:beginningOfWeek];
    }
    
    // 不可计算时，走下面的流程（正常应该不走下面）
    // couldn't calc via range, so try to grab Sunday, assuming gregorian style
    // Get the weekday component of the current date
    NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
    
    /*
     Create a date components to represent the number of days to subtract from the current date.
     The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
     */
    NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
    [componentsToSubtract setDay: 0 - [weekdayComponents weekday]];
    beginningOfWeek = nil;
    beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];
    
    //normalize to midnight, extract the year, month, and day components and create a new date from those components.
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                               fromDate:beginningOfWeek];
    return [calendar dateFromComponents:components];
}
//返回当前天的年月日.
- (NSDate *)beginningOfDay {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                               fromDate:self];
    return [calendar dateFromComponents:components];
}
//返回该月的第一天
- (NSDate *)beginningOfMonth
{
    return [self dateAfterDay:(int)(-[self getDay] + 1)];
}
//该月的最后一天
- (NSDate *)endOfMonth
{
    return [[[self beginningOfMonth] dateAfterMonth:1] dateAfterDay:-1];
}

//返回当前周的周末(周天作为本周最后一天)
- (NSDate *)endOfWeek {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
    // 如果是周天，就减去1，算成上周的
    if (1 == [weekdayComponents weekday]) {
        [componentsToAdd setDay:([weekdayComponents weekday] - 1)];
    }
    else
    {
        [componentsToAdd setDay:(7 - [weekdayComponents weekday] + 1)];
    }
    NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
    
    return endOfWeek;
}

//返回离当前时间几天后的本周第一天(周一作为本周第一天)
- (NSDate *)beginOfWeekWithBetweenDay:(NSInteger)betweenDay {
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:self];
    interval += 24*60*60*betweenDay;
    NSDate *tempDate = [self dateByAddingTimeInterval:interval];
    
    // 当前日期几天后的那周的开始（周一）
    NSDate *currentMonday = [tempDate beginningOfWeek];
    currentMonday = [currentMonday dateByAddingTimeInterval:[zone secondsFromGMTForDate:currentMonday]];

    return currentMonday;
}

//返回离当前时间几天后的本周最后一天(周天作为本周最后一天)
- (NSDate *)endOfWeekWithBetweenDay:(NSInteger)betweenDay {
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:self];
    interval += 24*60*60*betweenDay;
    NSDate *tempDate = [self dateByAddingTimeInterval:interval];
    
    // 当前日期几天后的那周的结束（周日）
    NSDate *currentSunday = [tempDate endOfWeek];
    return currentSunday;
}
// 返回当前周的周天
- (NSInteger)sundayOfWeek
{
    // largely borrowed from "Date and Time Programming Guide for Cocoa"
    // we'll use the default calendar and hope for the best
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *beginningOfWeek = nil;
    BOOL ok = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
                           interval:NULL forDate:self];
    if (ok) {
        return [[NSNumber numberWithDouble:[beginningOfWeek timeIntervalSince1970]] integerValue];
    }
    
    // couldn't calc via range, so try to grab Sunday, assuming gregorian style
    // Get the weekday component of the current date
    NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
    
    /*
     Create a date components to represent the number of days to subtract from the current date.
     The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
     */
    NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
    [componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
    beginningOfWeek = nil;
    beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];
    
    //normalize to midnight, extract the year, month, and day components and create a new date from those components.
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                               fromDate:beginningOfWeek];
    NSDate *beginOfWeek = [calendar dateFromComponents:components];
    return [[NSNumber numberWithDouble:[beginOfWeek timeIntervalSince1970]] integerValue];
}
// 返回当前周的周六
- (NSInteger)SaturdayOfWeek
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
    // to get the end of week for a particular date, add (7 - weekday) days
    [componentsToAdd setDay:(7 - [weekdayComponents weekday])];
    NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
    return [[NSNumber numberWithDouble:[endOfWeek timeIntervalSince1970]] integerValue];
}

+ (NSString *)dateFormatString {
    return @"yyyy-MM-dd";
}

+ (NSString *)timeFormatString {
    return @"HH:mm:ss";
}

+ (NSString *)timestampFormatString {
    return @"yyyy-MM-dd HH:mm:ss";
}

// preserving for compatibility
+ (NSString *)dbFormatString {
    return [NSDate timestampFormatString];
}

+ (NSString *)chFormatString
{
    return [NSString stringWithFormat:@"yyyy%@MM%@dd%@ HH:mm:ss",NSLocalizedString(@"year",nil),NSLocalizedString(@"month",nil),NSLocalizedString(@"day",nil)];
}

- (BOOL)isToday
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *componentsSelf = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:self];
    
    NSDate *today = [[NSDate alloc] init];
    NSDateComponents *compomentsToday = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:today];
    
    return componentsSelf.year == compomentsToday.year && componentsSelf.month == compomentsToday.month && componentsSelf.day == compomentsToday.day;
}

- (int)daysAgoWithToday
{
    NSDate *today = [[NSDate alloc] init];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitDay fromDate:today toDate:self options:0];
    int days =(int)[components day] + 1;
    return days;
}

+ (NSString *)getTodayDate
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *compoments = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSWeekdayCalendarUnit fromDate:now];
    
    return [NSString stringWithFormat:@"%02d-%02d",[compoments month],[compoments day]];
}

+ (NSString *)getTodayWeekday
{
    //    NSArray * arrWeek = @[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    NSArray * arrWeek = @[@"星期天",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *compoments = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSWeekdayCalendarUnit fromDate:now];
    
    return [NSString stringWithFormat:@"%@",[arrWeek objectAtIndex:[compoments weekday] - 1]];
}

+ (NSString *)getTodayWeekdayAndDate
{
    NSArray * arrWeek = @[@"星期天",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *compoments = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSWeekdayCalendarUnit fromDate:now];
    
    return [NSString stringWithFormat:@"%@ %02d-%02d",[arrWeek objectAtIndex:[compoments weekday] - 1],[compoments month],[compoments day]];
}

// 得到给定日期的那天开始即那天的零点
- (NSDate *)dateByMovingToBeginningOfDay
{
    unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
    [parts setHour:0];
    [parts setMinute:0];
    [parts setSecond:0];
    return [[NSCalendar currentCalendar] dateFromComponents:parts];
    
}//同理可以写出得到给定日期的那天的结束时间的函数

// 是否为下周（周一为第一天，周日为最后一天）
+ (BOOL)isNextWeek:(UInt64)UInt64Date
{
    NSDate *now = [[NSDate date] dateByMovingToBeginningOfDay];
    NSDate *currentMonday = [now getMonday];    // 本周开始（周一）
    //    NSDate *currentSunday = [now getSunday];    // 本周结束（周日）
    
    NSDate *temp = [NSDate dateWithTimeIntervalSince1970:UInt64Date/1000];
    NSDate *monday = [temp getMonday];  // 该天的一周开始（周一）
    //    NSDate *sunday = [temp getSunday];  // 该天的一周结束（周日）
    
    //    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //    NSInteger interval = [zone secondsFromGMTForDate:temp];
    //    NSDate *tempDate = [temp dateByAddingTimeInterval:interval];
    
    // 本周日
    if ([currentMonday isEqualToDate:monday]) {
        return NO;
    }
    
    // 下周日
    
    // 周一到周六：（起始周的时间相同）
    //    if ([currentMonday isEqualToDate:currentMonday]) {
    //        return NO;
    //    }
    
    return YES;
}

//    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];//前一天
//    NSDate *nextDat = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];//后一天

// 获取该周的周一（中国算法）
- (NSDate *)getMonday
{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:self];
    NSDate *tempDate = [self dateByAddingTimeInterval:interval];
    
    NSDate *currentSunday = [[tempDate beginningOfWeek] dateByAddingTimeInterval:interval]; // 本周开始（周日）
    
    // 如果是周日要 减6天
    if ([tempDate isEqualToDate:currentSunday]) {
        return [NSDate dateWithTimeInterval:-24*60*60*6 sinceDate:currentSunday];
    }
    
    return [NSDate dateWithTimeInterval:24*60*60 sinceDate:currentSunday];
}

// 获取该周的周日（中国算法）
- (NSDate *)getSunday
{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:self];
    NSDate *tempDate = [self dateByAddingTimeInterval:interval];
    
    NSDate *currentSunday = [[tempDate beginningOfWeek] dateByAddingTimeInterval:interval]; // 本周开始（周日）
    NSDate *currentSaturday = [self endOfWeek]; // 本周结束（周六）
    
    if ([tempDate isEqualToDate:currentSunday]) {
        return tempDate;
    }
    
    return [[NSDate dateWithTimeInterval:24*60*60 sinceDate:currentSaturday]dateByAddingTimeInterval:interval];
}


//传入今天的时间，返回明天的时间
+ (NSDate *)getYesterdayDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]-1)];
    
    NSDate *day = [gregorian dateFromComponents:components];
    return day;
}

// 获取明天的日期
+ (NSDate *)getTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *day = [gregorian dateFromComponents:components];
    return day;
}

// 获取几天后的日期
+ (NSString *)getStrDate:(NSString *)strDate betweenDays:(NSInteger)days withFormat:(NSString *)strFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:strFormat];
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [dateFormatter setTimeZone:timeZone];
    NSDate *birthdayDate = [dateFormatter dateFromString:strDate];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:birthdayDate];
    [components setDay:([components day]+days)];
    NSDate *date = [gregorian dateFromComponents:components];
    NSString *strRetDate = [dateFormatter stringFromDate:date];
    return strRetDate;
}

// 获取上个月的日期
+ (NSDate *)getLastMonth:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setMonth:([components month]-1)];
    
    NSDate *day = [gregorian dateFromComponents:components];
    return day;
}

// 获取当前是星期几
+ (NSString *)strWeekDay:(NSString *)strDate withFormat:(NSString *)strFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:strFormat];
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [dateFormatter setTimeZone:timeZone];
    NSDate *date = [dateFormatter dateFromString:strDate];
    NSString *strWeekDay = [date strWeekDayWithPrefix:@"周"];
    return strWeekDay;
}

// 循环生成数字(年份), 到当前截止
+ (NSArray <NSString *>*)makeCycleNumberWithBegin:(NSUInteger)begin
{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSString *year = [formatter stringFromDate:nowDate];
    int endYear = [year intValue];
    int startYear = 2000;
    NSMutableArray *yearArr = [[NSMutableArray alloc] init];
    for (; endYear >= startYear; endYear--) {
        [yearArr addObject:[NSString  stringWithFormat:@"%d", endYear]];
    }
    return [yearArr copy];
}


@end
